﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BricksProblemSolver
{
    public static class Extensions
    {
        public static T CloneRow<T>(this T @this)
            where T : class, IBrickRow
        {
            return @this.Clone() as T;
        }

        public static IEnumerable<IEnumerable<T>> Partition<T>(this IEnumerable<T> @this, int partitionSize)
        {
            int offset = 0;
            var fullArray = @this.ToArray();
            if (partitionSize <= 0)
            {
                partitionSize = fullArray.Length;
            }
            for (int i = 0; i < @this.LongCount()/partitionSize; ++i)
            {
                yield return new ArraySegment<T>(fullArray, offset, partitionSize);
                offset += partitionSize;
            }
            if (offset < fullArray.Length)
            {
                yield return new ArraySegment<T>(fullArray, offset, fullArray.Length - offset);
            }
        }

        public static void ForEach<T>(this IEnumerable<T> @this, Action<T> action)
        {
            foreach(var item in @this)
            {
                var temp = item;
                action(temp);
            }
        }

        public static IDisposable LogPerformance(this ILog Logger, string messageFormat, params object[] objs)
        {
            return new Disposable(timeCost => Logger.Write(string.Format(messageFormat, objs) + " Cost: {0:n3}", timeCost));
        }

        private class Disposable : IDisposable
        {
            private readonly System.Diagnostics.Stopwatch _watch = new System.Diagnostics.Stopwatch();
            private readonly Action<double> _action;

            public Disposable(Action<double> action)
            {
                _action = action;
                _watch.Start();
            }

            public void Dispose()
            {
                _watch.Stop();
                _action(_watch.Elapsed.TotalSeconds);
            }
        }
    }
}
